<template>
  <div class="realEstate">
    <div class="layui-panel">
      <div class="p-12">
        <div class="title">采购目录</div>
        <div class="pt-6">
          <form class="layui-form" action="">
            <div class="layui-row">
              <div class="layui-col-xs3">
                <div class="layui-form-item">
                  <label class="layui-form-label label-width"
                    >采购编码</label
                  >
                  <div class="layui-input-inline layui-input-wrap">
                    <input
                      type="text"
                      name="unitNumber"
                      placeholder="请输入"
                      autocomplete="off"
                      lay-affix="clear"
                      class="layui-input"
                    />
                  </div>
                </div>
              </div>
              <div class="layui-col-xs3">
                <div class="layui-form-item">
                  <label class="layui-form-label label-width"
                  >采购名称</label
                  >
                  <div class="layui-input-inline layui-input-wrap">
                    <input
                        type="text"
                        name="unitNumber"
                        placeholder="请输入"
                        autocomplete="off"
                        lay-affix="clear"
                        class="layui-input"
                    />
                  </div>
                </div>
              </div>
              <div class="layui-col-xs3">
                <div class="layui-form-item">
                  <label class="layui-form-label label-width"
                  >资产分类</label
                  >
                  <div class="layui-input-inline layui-input-wrap">
                    <input
                        type="text"
                        name="unitNumber"
                        placeholder="请输入"
                        autocomplete="off"
                        lay-affix="clear"
                        class="layui-input"
                    />
                  </div>
                </div>
              </div>
<!--              <div class="layui-col-xs3">
                <div class="layui-form-item">
                  <label class="layui-form-label">采购名称</label>
                  <div class="layui-input-inline">
                    <select name="currentStatus">
                      <option value=""></option>
                      <option value="已备案">已备案</option>
                      <option value="未备案">未备案</option>
                    </select>
                  </div>
                </div>
              </div>-->
<!--              <div class="layui-col-xs3">
                <div class="layui-form-item">
                  <label class="layui-form-label">归管部门</label>
                  <div class="layui-input-inline layui-input-wrap">
                    <input
                      type="text"
                      name="department"
                      autocomplete="off"
                      placeholder="请输入"
                      lay-affix="clear"
                      class="layui-input"
                    />
                  </div>
                </div>
              </div>-->
              <div class="layui-col-xs3">
                <button
                  class="layui-btn layui-btn-normal"
                  lay-submit
                  lay-filter="table-search"
                  type="button"
                >
                  <i class="layui-icon layui-icon-down layui-icon-search"></i>
                  搜索
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
    <div class="layui-panel mt-20">
      <div class="flex-end mt-12 mr-12">
        <button
          type="button"
          class="layui-btn layui-bg-blue"
          lay-on="openDialog"
        >
          同步
        </button>
      </div>
      <div class="p-12">
        <table
          class="layui-hide"
          id="ID-table-demo-data"
          lay-filter="ID-table-demo-data"
        ></table>
      </div>
    </div>
    <div id="barDemo" style="display: none">
      <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs layui-bg-blue" lay-event="edit"
          >映射</a
        >
<!--        <a class="layui-btn layui-btn-xs layui-bg-blue" lay-event="del">删除</a>-->
      </div>
    </div>
    <addDialog v-show="false" ref="addDialog"></addDialog>
  </div>
</template>

<script>
import addDialog from "@/views/purchaseDirMapping/components/addView.vue";
import {
  addReal_estate,
  delReal_estate,
  editReal_estate,
} from "@/api/real_estate_ledger";
export default {
  components: {
    addDialog,
  },
  data() {
    return {
      addOfEdit: "",
      fileId: "",
      departmentId: "",
      token:
          localStorage.getItem("foxnic-web")?.token ||
          'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGwiLCJ1aWQiOiIxMTA1ODgzNDgxMDExNjU5MTEiLCJhdWQiOiJhZG1pbiIsImlzcyI6ImZlbG9yZC5jbiIsInR5cGUiOiJhY2Nlc3MiLCJleHAiOiIyMDI0LTA2LTA2IDE3OjE2OjA3IiwiaWF0IjoiMjAyNC0wNi0wNiAxNjo0NjowNyIsImp0aSI6ImRmZWM2MmYyLTEzMDctNGIwNC05MjFiLTdkNTA1ZmQzMGVmYiJ9.AzrrRXYCEd_9cr1zKPasOCWQQFlQFP8-r6BI8AVrw16o6Z2a4IspFg6Aa7Q1_8CC10MkXt2VFaP1ViuG6MtoupLE0zgnS1B9P9QSzPkKmroe53wgKkOk9_ND_G38iN_KQrYqR_fjWPmReffxZKywskNzfCcS9QmVMluyG3WpRFilXoJHEJ8V5N84P3qX2Ot2tzr9D-qEbDXPN1UTlV4Rzh2TH_Xoi4vAk5FXtVRs0AUx1vWJ8o8hNbt95NKi2yDJQ7gH2zkLEalra7clxMpxxN8vfU2oGBC9gRsJrNaT_PhUXl77ts9LHV7cjVOT4NBI0eMGIjiMwathTTbaUb4LXQ'
      }
  },
  mounted() {
    window.layui.use(["table", "form", "jquery", "treeSelect"], async () => {
      var table = window.layui.table;
      const form = window.layui.form;
      const util = window.layui.util;
      const layer = window.layui.layer;
      const laydate = window.layui.laydate;
      const upload = window.layui.upload;
      const $ = window.layui.jquery;
      const treeSelect = window.layui.treeSelect;
      this.dialog = ""; // 弹框
      // 日期初始化
      laydate.render({
        elem: "#issuingDate",
      });
      laydate.render({
        elem: "#endDate",
      });
      laydate.render({
        elem: "#startDate",
      });
      uploadFormValue.call(this);
      // 已知数据渲染
      const tableIns = table.render({
        elem: "#ID-table-demo-data",
        url:
          process.env.VUE_APP_BASE_API +
          "/service-eam/gf-purchase-dir-mapping/query-list",
        method: "post",
        headers: {
          Authorization: "Bearer " + this.token,
        },
        request: {
          //自定义 page  limit
          pageName: "pageIndex",
          limitName: "pageSize",
        },
        cols: [
          [
            //标题栏
            {
              field: "purchaseCode",
              title: "采购编码",
              width: 200,
              sort: true,
            },
            { field: "purchaseName", title: "采购名称", width: 200 },
            { field: "assetCategoryName", title: "资产分类", width: 200 },
            { field: "remark", title: "备注", width:200 },
          /*  { field: "propertyType", title: "物业类型", width: 100 },
            { field: "purpose", title: "用途", width: 80 },
            { field: "currentStatus", title: "当前状态", width: 100 },
            { field: "address", title: "所属地址" },
            { field: "department", title: "归管部门", width: 120 },
            { field: "registrar", title: "登记人", width: 80 },
            { field: "createTime", title: "登记时间", width: 120 },*/
            {
              field: "right",
              title: "操作",
              width: 134,
              minWidth: 125,
              fixed: "right",
              toolbar: "#barDemo",
            },
          ],
        ],
        parseData: function (res) {
          return {
            code: res.code, //解析接口状态
            msg: res.message, //解析提示文本
            count: res.data.totalRowCount, //解析数据长度
            data: res.data, //解析数据列表
          };
        },
        page: true, // 是否显示分页
        limits: [5, 10, 15],
        limit: 5, // 每页默认显示的数量
      });
      /**
       * 打开新增弹框
       */
      util.on("lay-on", {
        openDialog: () => {
          //每次打开清空表单
          $(".reset_from").click();
          this.addOfEdit = "add";
          form.render();
          this.fileId = "";
          this.departmentId = "";
          // 重置附件
          $(".isShow-style").css("display", "flex");
          $("#ID-upload-demo-preview").addClass("layui-hide");
          this.dialog = layer.open({
            title: "采购目录",
            type: 1,
            offset: "t",
            anim: 0,
            area: ["700px", "100%"],
            shade: 0.1,
            shadeClose: true,
            id: "ID-demo-layer-direction-t",
            content: $("#add_dialog"),
          });
        },
      });
      form.render();
      /**
       * 表格按钮操作
       */
      table.on("tool(ID-table-demo-data)", (obj) => {
        const data = obj.data;
        if (obj.event === "del") {
          const configDialog = layer.confirm(
            "确定删除吗",
            { icon: 3, title: "删除确认" },
            async function () {
              const res = await delReal_estate(data.id);
              if (res.code === "00") {
                layer.msg("删除成功", { icon: 1 });
                layer.close(configDialog);
                tableIns.reload();
              } else {
                layer.msg("删除失败", { icon: 2 });
              }
            }
          );
        }
        if (obj.event === "edit") {
          this.addOfEdit = "edit";
          this.fileId = "";
          this.departmentId = "";
          this.dialog = layer.open({
            title: "采购目录",
            type: 1,
            offset: "t",
            anim: 0,
            area: ["800px", "100%"],
            shade: 0.1,
            shadeClose: true,
            id: "ID-demo-layer-direction-t",
            content: $("#add_dialog")
          });
          uploadFormValue.call(this, obj, data, true);
        }
      });
      /**
       * 页面条件查询
       */
      form.on("submit(table-search)", async (data) => {
        const field = data.field;
        tableIns.reload({
          url:
            process.env.VUE_APP_BASE_API +
            "/service-eam/gf-real-estate/query-paged-list",
          page: {
            pageIndex: 1,
          },
          where: field,
        });
      });
      function uploadFormValue(obj, data, isEdit = false) {
        // 回显
        /** 处理日期格式 */
        if(isEdit) {
          data.endDate = data.endDate && data.endDate.split(" ")[0];
          data.issuingDate = data.issuingDate && data.issuingDate.split(" ")[0];
          data.startDate = data.startDate && data.startDate.split(" ")[0];
        }
        form.val("formTeacherFilter", data);
        // this.$refs.addDialog.echoData(data?.deptId);
        if (this.addOfEdit === "edit") {
          this.$refs.addDialog.echoData(data.deptId);
        }
        // 照片回显
        if (isEdit) {
          if(!data.attachment) {
            $(".isShow-style").css("display", "flex");
            $("#ID-upload-demo-preview").addClass("layui-hide");
          }else {
            const imageUrl =
            process.env.VUE_APP_BASE_API +
            "/service-storage/sys-file/image?id=" +
            data.attachment;
          $(".isShow-style").css("display", "none");
          $("#ID-upload-demo-preview")
            .removeClass("layui-hide")
            .find("img")
            .attr("src", imageUrl);
          }
        }
        form.on("submit(add_submit)", async (res) => {
          let field = res.field;
          const newArr = {};
          for (let key in field) {
            if (field[key]) {
              newArr[key] = field[key];
            }
          }
          if (this.addOfEdit !== "edit") {
            newArr.attachment = this.fileId;
            newArr.deptId = this.departmentId;
            newArr.department = this.selectName;
            const result = await addReal_estate(newArr);
            if (result.code === "00") {
              layer.msg("新增成功", { icon: 1 });
              layer.close(this.dialog);
              tableIns.reload();
            } else {
              layer.msg("新增失败", { icon: 2 });
            }
            return;
          }
          newArr.id = data.id;
          newArr.attachment = this.fileId || newArr.attachment;
          newArr.deptId = this.departmentId || newArr.deptId;
          newArr.department = this.selectName || newArr.department;
          const result = await editReal_estate(newArr);
          if (result.code === "00") {
            layer.msg("修改成功", { icon: 1 });
            layer.close(this.dialog);
            tableIns.reload();
          } else {
            layer.msg("修改失败", { icon: 2 });
          }
        });
      }
      /**
       * 树形下拉组件
       */
      treeSelect.render({
        // 选择器
        elem: "#tree1",
        // 数据
        data:
          process.env.VUE_APP_BASE_API +
          '/service-pcm/pcm-catalog/query-nodes',
        // 异步加载方式：get/post，默认get
        type: "post",
        headers: {
          Authorization: "Bearer " + this.token,
        },
        style: {
          folder: {
            // 父节点图标
            enable: true, // 是否开启：true/false
          },
          line: {
            // 连接线
            enable: true, // 是否开启：true/false
          },
        },
        // 占位符
        placeholder: "请选择",
        // 是否开启搜索功能：true/false，默认false
        search: true,
        // 点击回调
        click: (d) => {
          this.departmentId = d.current.id;
          this.selectName = d.current.name;
        },
        // 加载完成后的回调函数
        success: (d) => {
          //             // 选中节点，根据id筛选
          // if (this.addOfEdit === "edit") {
            // treeSelect.checkNode("tree1", this.departmentId);
          // }
          //             // 选中节点，根据id筛选
          /*console.log('====',departmentId)
          if(departmentId) {
            this.treeSelect.checkNode("tree1", departmentId);
            const dom = document.querySelectorAll('#department-style .layui-treeSelect')
            dom[dom.length - 1].remove()
          }else {
            this.treeSelect.checkNode("tree1", null);
            const dom = document.querySelectorAll('#department-style .layui-treeSelect')
            dom[dom.length - 1].remove()
          }*/
          /*// 添加点击事件监听
          this.treeSelect.on("click(tree1)", (res) => {
            // res.node.id 通常表示被点击节点的ID
            this.loadSubNodes(res.node.id);
          });*/
// 添加点击事件监听
          this.treeSelect.on("click(tree1)", async (res) => {
            // res.node.id 通常表示被点击节点的ID
            try {
              // 构造请求URL，包含parentId和isLoadAllDescendants参数
              const url = new URL(`${process.env.VUE_APP_BASE_API}/service-pcm/pcm-catalog/children/${res.node.id}`);
              url.searchParams.append('parentId', res.node.id); // 假设父节点ID需要作为参数传递
              url.searchParams.append('isLoadAllDescendants', '0'); // 假设需要传递isLoadAllDescendants标志

              const response = await fetch(url.toString(), {
                method: 'GET',
                headers: {
                  'Authorization': 'Bearer ' + this.token,
                  // 其他可能需要的头部信息
                },
              });

              if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
              }

              const subNodes = await response.json();

              // 更新树形组件的数据
              this.treeSelect.updateNode("tree1", { id: res.node.id, children: subNodes });
            } catch (error) {
              console.error("Error loading sub nodes:", error);
            }
          });
        },
      });
      /** 弹框取消按钮监听 */
      $(".cancel").on("click", () => {
        layer.close(this.dialog);
      });
      /**  上传图片 */
      upload.render({
        elem: "#ID-upload-demo-drag",
        accept: "file",
        url: process.env.VUE_APP_BASE_API + "/service-storage/sys-file/upload",
        headers: {
          Authorization: "Bearer " + this.token,
        },
        before: (obj) => {
          obj.preview((index, file, result) => {
            this.fileImage = result;
          });
        },
        done: (res) => {
          if (res.code === "00") {
            layer.msg("上传成功");
            $(".isShow-style").css("display", "none");
            $("#ID-upload-demo-preview")
              .removeClass("layui-hide")
              .find("img")
              .attr("src", this.fileImage);
            // 保存文件id
            this.fileId = res.data[0].fileId;
          }
        },
      });
    });
  },
};
</script>

<style scoped lang="scss">
.realEstate {
  .layui-input-inline {
    width: 150px;
  }
}
.title {
  font-size: 16px;
  color: #000000;
}

.label-width {
  width: 100px;
}

.p-12 {
  padding: 12px;
}

.pt-6 {
  padding-top: 6px;
}

.mt-20 {
  margin-top: 20px;
}
.image {
  width: 50px;
  height: 50px;
}
</style>
